package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Semaphore 示例3
 *
 * @author ziyucoding
 * @date 2022-10-27
 **/
@Slf4j
public class SemaphoreExample3 {

    /**
     * 同时并发执行的线程数
     */
    private static int threadTotal = 10;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadTotal; i++) {
            final int num = i;
            executorService.execute(() -> {
                try {
                    if (semaphore.tryAcquire()) {// 尝试获取一个许可
                        test(num);
                        semaphore.release(); // 释放一个许可
                    }
                } catch (Exception e) {
                    log.error("发生异常", e);
                }
            });
        }
        log.info("finish");
        executorService.shutdown();
    }

    /**
     * 测试
     *
     * @param num
     * @return void
     **/
    private static void test(int num) throws InterruptedException {
        log.info("threadNum:{}", num);
        Thread.sleep(1000);
    }
}
